import axios from 'axios'
import { defineStore } from 'pinia'
import useUserInfo from './useUserInfo'

const config = {
  development: Object.freeze({
    /** 协议 */
    protocol: 'http',
    /** 域名 */
    domainName: '127.0.0.1',
    /** ipv4端口号 */
    ipv4Prot: 5407
  }),
  production: Object.freeze({
    protocol: 'https',
    domainName: 'wuhaochao.top',
    ipv4Prot: 5408
  })
}

/** 项目运行环境 */
export const NODE_ENV = process.env.NODE_ENV as 'development' | 'production'
/** 是否为客户端 */
export const IS_ELECTRON = !!process.env.IS_ELECTRON

const envState = config[NODE_ENV]
let ipv4Origin = `${envState.protocol}://${envState.domainName}`
if (NODE_ENV === 'development') ipv4Origin += `:${envState.ipv4Prot}`
const ipv6Origin = `${envState.protocol}://ipv6.${envState.domainName}`

const state = {
  ...envState,
  /** 项目运行环境 */
  NODE_ENV,
  /** 是否为客户端 */
  IS_ELECTRON,
  /** 是否为 ipv6 */
  isIpv6: false,
  /** 域源 */
  origin: ipv4Origin,
  /** ipv4地址 */
  ipv4Origin,
  /** ipv6地址 */
  ipv6Origin
}

export const useEnv = defineStore('env', {
  state: () => state,
  getters: {
    /** 接口地址 */
    apiUrl: state => state.origin + '/api',
    /** 静态资源地址 */
    staticUrl: state => state.origin + '/static',
    /** nas文件地址 */
    nasFileUrl: state => `${state.origin}/static/users/${useUserInfo().id}/nas/file`,
    /** nas缩略图地址 */
    nasThumbUrl: state => `${state.origin}/static/users/${useUserInfo().id}/nas/thumbnail`
  },
  actions: {
    /** 检查客户端是否支持 ipv6 */
    async checkIsIpv6() {
      return axios
        .get(ipv6Origin + '/api/user/check_phone')
        .then(() => {
          this.origin = ipv6Origin
          this.isIpv6 = true
        })
        .catch(() => {
          this.origin = ipv4Origin
          this.isIpv6 = false
        })
    }
  }
})
